package com.jsb.common.interceptor;

import java.io.PrintWriter;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

public class SessionTimeoutInterceptor extends HandlerInterceptorAdapter {

    private List<String> allowUrls;

    public List<String> getAllowUrls() {
        return allowUrls;
    }

    public void setAllowUrls(List<String> allowUrls) {
        this.allowUrls = allowUrls;
    }

    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        String requestUrl = request.getRequestURI();
        String u = request.getHeader("Referer");
        for (String url : allowUrls) {
            if (requestUrl.endsWith(url)) {
                return true;
            }
        }
        if (request.getSession().getAttribute("loginUser") == null) {
            if ("XMLHttpRequest".equalsIgnoreCase(request.getHeader("X-Requested-With")) || request.getParameter("ajax") != null) {
                PrintWriter out = response.getWriter();
                out.println("{\"statusCode\":\"" + 301 + "\",\"message\":\"页面过期，请重新登录\"}");
                return false;
            } else {
                PrintWriter out = response.getWriter();
                StringBuilder builder = new StringBuilder();
                builder.append("<html><meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" />");
                builder.append("<script type=\"text/javascript\">");
                builder.append("var logUrl = \""+request.getContextPath()+"/toLogin.do\"; ");
                builder.append("window.top.location.href = logUrl  ");
                builder.append("</script></html>");
                out.print(builder.toString());
                out.close();
                return false;
            }
        }
        return true;
    }
}
